﻿using BaseTool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StructuredLightSystemUI
{
    /// <summary>
    /// 主窗体
    /// </summary>
    public partial class MainForm : InnerForm
    {
        #region 构造、初始化
        /// <summary>
        /// 构造
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
        }
        //加载前
        private void MainForm_Load(object sender, EventArgs e)
        {
            //日志事件
            Log.LogAction += LogAction;
            Machine.LogControlVisableChange += LogControlVisableChange;

            //版本信息
            tsl_versions.Text = MyGlobal.Versions;
            Log.SaveLog(tsl_versions.Text, LogType.Run, false);

            //状态栏信息
            Machine.StatusBarAction += StatusBarAction;
            StatusBarAction(-1, "", Color.Black);

            //子页面事件添加
            conMain.ChangePage += ChangePage;

            //主页面刷新事件
            Machine.MainFormRefreshAction += Refresh;
        }
        //显示后
        private void MainForm_Shown(object sender, EventArgs e)
        {
            //截图控件传入全局参数
            Rectangle rectangle = System.Windows.Forms.Screen.GetBounds(this);
            ScreenControl.SetFullScreenSize(rectangle.Width, rectangle.Height);
            ScreenControl.SetFormScreenSize(this.Location.X, this.Location.Y, this.Size.Width, this.Size.Height);

            //静态参数初始化
            MyGlobal.Init();
            //初始化型号信息
            RefreshProductName();

            //初始化下拉框（页面选项）
            InitPage();
            //切换主页面
            ChangePage(ToolStripMenuPage.主页面);
        }
        //正在关闭
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Machine.WillExit = true;

            //日志事件
            Log.LogAction -= LogAction;
            Machine.LogControlVisableChange -= LogControlVisableChange;

            //切换页面
            ChangePage(ToolStripMenuPage.无);

            //子页面事件删除
            conMain.ChangePage -= ChangePage;
        }
        //已关闭
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        /// <summary>
        /// 初始化页面选项
        /// </summary>
        private void InitPage()
        {
            string[] pageNames = Enum.GetNames(typeof(ToolStripMenuPage));
            foreach (string pageName in pageNames)
            {
                if (pageName == ToolStripMenuPage.无.ToString())
                    continue;

                ToolStripMenuItem toolStripItem = new ToolStripMenuItem(pageName);
                this.tssb_page.DropDownItems.Add(toolStripItem);
            }
        }
        #endregion



        #region 切换页面
        /// <summary> 主页面 </summary>
        private ConMain conMain = new ConMain();
        /// <summary> 相机测试页面 </summary>
        private ConCamera conCamera = new ConCamera();
        /// <summary> 投影仪测试页面 </summary>
        private ConProjector conProjector = new ConProjector();
        /// <summary> 标定页面 </summary>
        private ConCalibration conCalibration = new ConCalibration();
        /// <summary> 重建页面 </summary>
        private ConReconstruct conReconstruct = new ConReconstruct();
        /// <summary> 点云显示页面 </summary>
        private ConPointCloudShow conPointCloudShow = new ConPointCloudShow();
        /// <summary> 辅助功能页面 </summary>
        private ConAuxiliaryFunction conAuxiliaryFunction = new ConAuxiliaryFunction();

        /// <summary> 当前页面 </summary>
        private ToolStripMenuPage CurrentPage = ToolStripMenuPage.无;
        /// <summary> 锁：切换页面 </summary>
        private readonly object lockChangePage = new object();

        //点击页面下拉框选项
        private void tssb_page_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ToolStripMenuPage newPage;
            if (Enum.TryParse(e.ClickedItem.Text, out newPage))
                ChangePage(newPage);
        }

        /// <summary>
        /// 切换页面
        /// </summary>
        /// <param name="changePage">需要切换的页面</param>
        private void ChangePage(ToolStripMenuPage changePage)
        {
            lock (lockChangePage)
            {
                if (changePage == CurrentPage)
                    return;
                try
                {
                    //先关闭
                    switch (CurrentPage)
                    {
                        case ToolStripMenuPage.主页面:
                            {
                                conMain.CloseControl();
                                break;
                            }
                        case ToolStripMenuPage.相机测试页面:
                            {
                                conCamera.CloseControl();
                                break;
                            }
                        case ToolStripMenuPage.投影仪测试页面:
                            {
                                conProjector.CloseControl();
                                break;
                            }
                        case ToolStripMenuPage.标定页面:
                            {
                                conCalibration.CloseControl();
                                break;
                            }
                        case ToolStripMenuPage.重建页面:
                            {
                                conReconstruct.CloseControl();
                                break;
                            }
                        case ToolStripMenuPage.点云显示页面:
                            {
                                conPointCloudShow.CloseControl();
                                break;
                            }
                        case ToolStripMenuPage.辅助功能页面:
                            {
                                conAuxiliaryFunction.CloseControl();
                                break;
                            }
                        case ToolStripMenuPage.无:
                        default:
                            {
                                break;
                            }
                    }
                    panelPage.Controls.Clear();
                    tssb_page.Text = changePage.ToString();
                    //再打开
                    switch (changePage)
                    {
                        case ToolStripMenuPage.主页面:
                            {
                                conMain.OpenControl();
                                conMain.Dock = DockStyle.Fill;
                                panelPage.Controls.Add(conMain);
                                break;
                            }
                        case ToolStripMenuPage.相机测试页面:
                            {
                                conCamera.OpenControl();
                                conCamera.Dock = DockStyle.Fill;
                                panelPage.Controls.Add(conCamera);
                                break;
                            }
                        case ToolStripMenuPage.投影仪测试页面:
                            {
                                conProjector.OpenControl();
                                conProjector.Dock = DockStyle.Fill;
                                panelPage.Controls.Add(conProjector);
                                break;
                            }
                        case ToolStripMenuPage.标定页面:
                            {
                                conCalibration.OpenControl();
                                conCalibration.Dock = DockStyle.Fill;
                                panelPage.Controls.Add(conCalibration);
                                break;
                            }
                        case ToolStripMenuPage.重建页面:
                            {
                                conReconstruct.OpenControl();
                                conReconstruct.Dock = DockStyle.Fill;
                                panelPage.Controls.Add(conReconstruct);
                                break;
                            }
                        case ToolStripMenuPage.点云显示页面:
                            {
                                conPointCloudShow.OpenControl();
                                conPointCloudShow.Dock = DockStyle.Fill;
                                panelPage.Controls.Add(conPointCloudShow);
                                break;
                            }
                        case ToolStripMenuPage.辅助功能页面:
                            {
                                conAuxiliaryFunction.OpenControl();
                                conAuxiliaryFunction.Dock = DockStyle.Fill;
                                panelPage.Controls.Add(conAuxiliaryFunction);
                                break;
                            }
                        case ToolStripMenuPage.无:
                        default:
                            {
                                break;
                            }
                    }

                }
                catch (Exception ex)
                {
                    Log.SaveError(ex, $"切换页面异常，{ex.Message}", LogType.Run);
                }
                finally
                {
                    CurrentPage = changePage;
                }
            }
        }
        #endregion

        #region 控件事件
        //图标点击事件
        private void pb_Icon_MouseClick(object sender, MouseEventArgs e)
        {
            AboutForm about = new AboutForm();
            about.ShowDialog();
        }
        //提示信息
        private void tsb_tip_Click(object sender, EventArgs e)
        {
            AboutForm about = new AboutForm();
            about.ShowDialog();
        }
        //打开型号下拉框选项
        private void tssb_product_DropDownOpening(object sender, EventArgs e)
        {
            tssb_product.DropDownItems.Clear();
            string[] products = PathTool.ReadProductList();
            foreach (string product in products)
            {
                ToolStripMenuItem toolStripItem = new ToolStripMenuItem(product);
                this.tssb_product.DropDownItems.Add(toolStripItem);
            }
        }
        //点击型号
        private void tssb_product_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == null)
                return;

            //切换新型号
            MyGlobal.ChangeProduct(e.ClickedItem.Text);

            //刷新型号名字
            RefreshProductName();
        }

        /// <summary>
        /// 刷新型号名字
        /// </summary>
        private void RefreshProductName()
        {
            tssb_product.Text = $"当前型号：{PathTool.ProductType}";
        }


        #endregion

        #region 日志事件
        /// <summary> 实时日志锁 </summary>
        private readonly object lockLog = new object();

        /// <summary>
        /// 日志控件显示/隐藏
        /// </summary>
        private void LogControlVisableChange()
        {
            splitContainer1?.Invoke((MethodInvoker)delegate
            {
                splitContainer1.Panel2Collapsed = !splitContainer1.Panel2Collapsed;
                Machine.LogControlVisableReadOnly = !splitContainer1.Panel2Collapsed;
            });
        }

        /// <summary>
        /// 日志事件
        /// </summary>
        /// <param name="logMessage"></param>
        private void LogAction(LogMessage logMessage)
        {
            rtb_log?.Invoke((MethodInvoker)delegate
            {
                try
                {
                    lock (lockLog)
                    {
                        //程序退出
                        if (Machine.WillExit)
                            return;

                        //不显示Log
                        if (logMessage == null || !logMessage.isShow)
                            return;

                        //判断log是否需要显示
                        switch (logMessage.logType)
                        {
                            case LogType.Run:
                            case LogType.Sensor:
                            default:
                                break;
                            case LogType.Error:
                                return;
                        }

                        //显示日志
                        if (rtb_log.Text.Length > 10000)
                            rtb_log.Clear();
                        rtb_log.Select(rtb_log.TextLength, 0);
                        rtb_log.SelectionColor = logMessage.color;
                        rtb_log.AppendText($"[{logMessage.time.ToString("HH:mm:ss")}] {logMessage.message}\r\n");
                        rtb_log.ScrollToCaret();
                        //rtb_log.Refresh();
                    }
                }
                catch (Exception ex)
                {
                    Log.SaveError(ex);
                }
            });
        }
        #endregion

        #region 杂项
        /// <summary> 状态栏锁 </summary>
        private readonly object lockProgressBar = new object();

        //默认计时器
        private void timerDefault_Tick(object sender, EventArgs e)
        {
            //当前时间
            tsl_time.Text = "当前时间：" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");

            //投影仪
            if (MyGlobal.ProjectorTool.IsOpen)
            {
                tsl_projector.Text = $"投影仪已连接";
                tsl_projector.Image = Properties.Resources.圆形_Green;
            }
            else
            {
                tsl_projector.Text = $"投影仪已断开";
                tsl_projector.Image = Properties.Resources.圆形_Gray;
            }

            //相机
            if (MyGlobal.CameraTool.IsConnected)
            {
                if (MyGlobal.CameraTool.IsGrabbing)
                {
                    tsl_camera.Text = $"相机已打开数据流";
                    tsl_camera.Image = Properties.Resources.圆形_Pink;
                }
                else
                {
                    tsl_camera.Text = $"相机已连接";
                    tsl_camera.Image = Properties.Resources.圆形_Green;
                }
            }
            else
            {
                tsl_camera.Text = $"相机已断开";
                tsl_camera.Image = Properties.Resources.圆形_Gray;
            }
        }
        /// <summary>
        /// 状态栏信息
        /// </summary>
        /// <param name="per"> 百分比（0-1,0-100） </param>
        /// <param name="info"> 短信息 </param>
        /// <param name="color"> 短信息颜色 </param>
        private void StatusBarAction(double per, string info, Color color)
        {
            ts_bottom.Invoke((MethodInvoker)delegate
            {
                lock (lockProgressBar)
                {
                    //进度条
                    if (per == -1)
                    {
                        tspb_progressBar.Visible = false;
                    }
                    else
                    {
                        tspb_progressBar.Visible = true;
                        if (per <= 0)
                            tspb_progressBar.Value = 0;
                        else if (per < 1)
                            tspb_progressBar.Value = (int)(per * 100);
                        else if (per == 1 || per >= 100)
                            tspb_progressBar.Value = 100;
                        else
                            tspb_progressBar.Value = (int)per;
                    }

                    //短信息
                    if (string.IsNullOrWhiteSpace(info) || info.Length > 10)
                        tsl_progressBar.Text = "";
                    else
                    {
                        tsl_progressBar.Text = info;
                        tsl_progressBar.ForeColor = color;
                    }

                    ts_bottom.Refresh();
                }
            });
        }
        #endregion

    }
}
